package com.google.code.p2pxmppclient;

import java.util.Collection;
import java.util.logging.Logger;

import org.jivesoftware.smack.Roster;
import org.jivesoftware.smack.RosterListener;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.packet.Presence;

import com.google.code.p2pxmppclient.notifyserver.NotifyServer;



/**
 * 
 * @author eliosh
 * @version $Rev$
 * @lastautorcommit $Author$
 * @lastdatecommit $Date$
 */
public class XMPPRosterListener implements RosterListener {

	private NotifyServer notifyServer;
	private XMPPConnection conn;
	private static final Logger log = Logger.getLogger(XMPPRosterListener.class.getCanonicalName());
	
	public XMPPRosterListener(NotifyServer notifyServer, XMPPConnection conn) {
		super();
		this.notifyServer = notifyServer;
		this.conn = conn;
	}

	@Override
	public void entriesAdded(Collection<String> arg0) {
		// Called when roster entries are added.
	}

	@Override
	public void entriesDeleted(Collection<String> arg0) {
		// Called when a roster entries are removed.
		
	}

	@Override
	public void entriesUpdated(Collection<String> arg0) {
		// Called when a roster entries are updated.
		
	}

	@Override
	public void presenceChanged(Presence presence) {
        // Called when the presence of a roster entry is changed.
		String from = presence.getFrom();
		String[] fromParts = from.split("/");
		String user = fromParts[0];
		Roster roster = conn.getRoster();
	    Presence bestPresence = roster.getPresence(user);
	    if (bestPresence.getType() == Presence.Type.available) {
	    	// notify messageBroker of new presence
	    	log.info(user + " return to be available");
	    	notifyServer.returnToAvailable(user);
	    }
	}

}
